import commentSchema from '../../models/comment'
module.exports = {
  async commentList (ctx, next) {
    console.log('----------------获取全部评论 comment/commentList-----------------------');
    let id = ctx.request.query.articleid;
    let ignore = {}
    try {
      let data = await ctx.findPage(commentSchema, {}, ignore, {sort: {time: -1}})
      if (!data) {
        ctx.resResult({commentlist: []}, '还没有评论呢')
      } else {
        ctx.resResult(data, 'success')
      }
    }catch(e) {
      ctx.resResultError(e)
    }
  },
  async comment (ctx, next) {
    console.log('----------------获取当前评论 comment/comment-----------------------');
    let id = ctx.request.query.articleid;
    let ignore = {
      'commentlist.contact': 0,
      'commentlist.reply.contact': 0
    }
    try {
      let data = await ctx.findOne(commentSchema, {articleid: id}, ignore)
      if (!data) {
        ctx.resResult({commentlist: []}, '还没有评论呢')
      } else {
        ctx.resResult(data, 'success')
      }
    }catch(e) {
      ctx.resResultError(e)
    }
  },
  async add (ctx, next) {
    console.log('----------------添加评论 comment/add-----------------------');
    let paramsData = ctx.request.body;
    const id = paramsData.articleid
    try {
      let data = await ctx.add(commentSchema, paramsData);
      console.log('ddd', data)
      ctx.resResult(data.commentlist[0], '添加成功!')
    }catch(e) {
      ctx.resResultError(e)
    }
  },
  async update (ctx, next) {
    console.log('----------------更新评论 comment/update-----------------------');
    let paramsData = ctx.request.body;
    let type = paramsData.type
    let articleid = paramsData.articleid
    if (type) {
      let commentid = paramsData.commentid
      try {
        let data = await ctx.update(commentSchema, {articleid: articleid, 'commentlist._id': commentid}, {
          '$push': {
            'commentlist.$.reply': {
              $each: [paramsData.replyItem],
              $sort: { time: -1 }
            }
          }})
        ctx.resResult(data, '更新成功!')
      } catch(e) {
        if (e === '暂无数据') {
          ctx.resResultError(e)
        }
      }
    } else {
      try {
        let data = await ctx.update(commentSchema, {articleid: articleid}, {
          '$push': {
            commentlist: {
              $each: [paramsData.commentItem],
              $sort: { time: -1 }
            }
          }
        })
        ctx.resResult(data, '更新成功!')
      } catch(e) {
        if (e === '暂无数据') {
          ctx.resResultError(e)
        }
      }
    }
  },
  async del (ctx, next) {
    console.log('----------------删除评论 comment/del-----------------------');
    let id = ctx.request.query.id
    try {
        ctx.remove(commentSchema, {_id: id})
        ctx.resResult({}, '删除成功!')
    }catch(e){
        ctx.resResultError(e)
    }
  }
}
